/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */
package be.destin.skos.xml;

import java.io.FileNotFoundException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.jasper.xmlparser.XMLChar;
import org.apache.log4j.Logger;

import be.destin.util.Util;

public class NoDTDInputStream extends FilterInputStream {

	/** log4j category */
	static Logger log = Logger.getLogger(NoDTDInputStream.class);

	boolean removeDTD = true;

	public NoDTDInputStream(InputStream input)
			throws FileNotFoundException {
		super(input);
		// TODO Auto-generated constructor stub
	}

	public int read(byte b[], int off, int len) throws IOException {
		int i = super.read(b,off,len);
		if (removeDTD && i > 0) {
			int readLen = i;
			while (readLen < len && readLen < 1000) { // Ensure <!DOCTYPE is reached!
				i = super.read(b,readLen,len-readLen);
				if (i <= 0) break;
				readLen += i;
			}
			int beg = Util.searchBuffer(b,readLen,XMLUtil.begDTDDecl,off);
			int end = 0;
			if (beg >= 0) {
				log.error("begin DTD: "+off+':'+beg+"/"+readLen);
				end = Util.searchBuffer(b,readLen,XMLUtil.endDTDDecl,off+beg);
				if (end > beg) {
					Util.moveBuffer(b,readLen,end+XMLUtil.endDTDDecl.length,beg);
					readLen = readLen - (end+XMLUtil.endDTDDecl.length - beg);
					removeDTD = false;
				}
			}
			i = readLen;
		}
		for (int j = 0; j < i; j++) {
			if (b[j] > 0) {
				if ( ! XMLChar.isValid(b[j])) {
					b[j] = ' '; // Put spaces where invalid characters pollute our file...
				}
			}
		}
		return i;
	}

	public boolean isRemoveDTD() {
		return removeDTD;
	}

	public void setRemoveDTD(boolean removeDTD) {
		this.removeDTD = removeDTD;
	}
}